package com.xius.interceptor;

import cn.hutool.core.util.StrUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @ClassName SqlInterceptor
 * @Description TODO
 * @Author 谭庆伟
 * @Date 2020/9/4 16:11
 * @Version 1.0
 **/
@Intercepts(value = {
        @Signature(
                type = Executor.class,
                method = "update",
                args = {MappedStatement.class, Object.class})})
public class SqlInterceptor implements Interceptor {
    /**
     * 创建时间
     */
    private static final String CREATE_TIME = "create_time";
    /**
     * 更新时间
     */
    private static final String UPDATE_TIME = "update_time";

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        // SQL操作命令
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        // 获取新增或修改的对象参数
        Object parameter = invocation.getArgs()[1];
        // 获取对象中所有的私有成员变量（对应表字段）
        LinkedHashMap<String,Object> parameMap = (LinkedHashMap<String, Object>) parameter;
        for (Map.Entry<String, Object> entry : parameMap.entrySet()) {
            String key = entry.getKey();
            if (StrUtil.contains(key,CREATE_TIME)) {
                if (SqlCommandType.UPDATE.equals(sqlCommandType)) {

                }
            }
            if (StrUtil.contains(key,UPDATE_TIME)) {
                if (SqlCommandType.UPDATE.equals(sqlCommandType)) {

                }
            }
        }

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

    @Override
    public void setProperties(Properties properties) {
    }

}